﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using GroupChat2013.Common;
using System.Threading;
using GroupChat2013.Main.Properties;
using System.IO;

namespace GroupChat2013.Main
{
    static class Program
    {
        [STAThread]
        private static void Main(string[] args)
        {
            bool initiallyOwned = true; //是否应拥有互斥体的初始所有权
            bool bCreatedNew = false; //是否被授予互斥体的初始所有权

            //初始化互斥体
            Mutex m = new Mutex(initiallyOwned, "GCSendMessage", out bCreatedNew);

            //如果为false,则程序已经启动
            if (!(initiallyOwned && bCreatedNew))
            {
                m.Close();

                //string strSend = args == null || args.Length <= 0 ? "Show" : args[0];
                string strSend = "Show";

                if (args != null && args.Length > 0 && args[0] == "0")
                {
                    strSend = args[0];
                }

                LogHelper.LogInfo(string.Format("程序已经启动 接受到的参数{0} ", strSend));
                LogHelper.LogInfo(string.Format("BaseDirectory:{0} ", AppDomain.CurrentDomain.BaseDirectory));

                SendMessage(strSend);
            }
            else //可以启动程序
            {
                try
                {
                    FrmLogin frmLogin = null;

                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    if (args != null && args.Length > 0)
                    {
                        string strSend = args[0];
                        if (strSend == "0")
                            return;

                        LogHelper.LogInfo(string.Format("程序正在启动 接受到的参数{0} ", strSend));
                        LogHelper.LogInfo(string.Format("BaseDirectory:{0} ", AppDomain.CurrentDomain.BaseDirectory));
                   
                        frmLogin = new FrmLogin(strSend);
                    }
                    else
                    {
                        frmLogin = new FrmLogin();
                    }

                    Application.Run(frmLogin);
                }
                catch (Exception ex)
                {
                    LogHelper.LogError(string.Format("Message:{0}/r/nStackTrace{1}", ex.Message, ex.StackTrace));
                    MessageBox.Show(ex.Message);
                }

                //释放互斥体
                m.ReleaseMutex();
            }
        }

        private static void SendMessage(string content)
        {
            IntPtr hwnd = default(IntPtr);
            string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConstClass.DataDirName);

            string CurrentIntPtr = Path.Combine(configPath, ConstClass.CurrentIntPtr);
            string ptrStr = string.Empty;

            FileStream fs = File.Open(CurrentIntPtr, FileMode.Open);
            using (StreamReader sr = new StreamReader(fs))
            {
                ptrStr = sr.ReadToEnd();
            }
            fs.Close();

            if (!string.IsNullOrEmpty(ptrStr))
                hwnd = (IntPtr)Convert.ToInt64(ptrStr);

            SendMessage(hwnd, content);
        }

        private static void SendMessage(IntPtr hander, string content)
        {
            int WINDOW_HANDLER = hander.ToInt32();
            if (WINDOW_HANDLER != 0)
            {
                byte[] sarr = System.Text.Encoding.Default.GetBytes(content);
                int len = sarr.Length;
                COPYDATASTRUCT cds;
                cds.dwData = (IntPtr)100;
                cds.lpData = content;
                cds.cbData = len + 1;
                WinApi.SendMessage(WINDOW_HANDLER, WinApi.WM_COPYDATA, 0, ref cds);
            }
        }

        public static Point GetLocation(int width, int height)
        {
            Random r = new Random();
            int n = r.Next(-20, 20);
            int x = (Screen.PrimaryScreen.WorkingArea.Width - width) / 2 + n;
            int y = (Screen.PrimaryScreen.WorkingArea.Height - height) / 2 + n;
            return new Point(x, y);
        }
    }
}
